<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能营养管理系统 - 用户仪表盘</title>
    <style>
        /* 基本样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8f9fa;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 15px;
        }
        
        /* 顶部导航 */
        .navbar {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            padding: 1rem 0;
            margin-bottom: 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .navbar-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .navbar-brand {
            font-size: 1.5rem;
            font-weight: bold;
            color: white;
            text-decoration: none;
        }
        
        .navbar-nav {
            display: flex;
            gap: 1rem;
        }
        
        .nav-link {
            color: white;
            text-decoration: none;
            padding: 0.5rem 1rem;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        
        .nav-link:hover {
            background-color: rgba(255,255,255,0.1);
        }
        
        /* 顶部显示区 */
        .top-section {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }
        
        .user-welcome {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }
        
        .welcome-text h2 {
            color: #007bff;
            margin-bottom: 0.5rem;
        }
        
        .welcome-text p {
            color: #6c757d;
            margin: 0;
        }
        
        .quick-actions {
            display: flex;
            gap: 1rem;
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #0056b3;
            transform: translateY(-2px);
        }
        
        .btn-outline-primary {
            background-color: transparent;
            color: #007bff;
            border: 2px solid #007bff;
        }
        
        .btn-outline-primary:hover {
            background-color: #007bff;
            color: white;
        }
        
        /* 营养进度区 */
        .nutrition-overview {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .nutrition-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            box-shadow: 0 2px 15px rgba(0,0,0,0.08);
            transition: transform 0.3s ease;
        }
        
        .nutrition-card:hover {
            transform: translateY(-5px);
        }
        
        .nutrition-icon {
            font-size: 2.5rem;
            margin-bottom: 1rem;
        }
        
        .nutrition-value {
            font-size: 1.5rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .nutrition-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .progress-ring {
            width: 80px;
            height: 80px;
            margin: 0 auto 1rem;
        }
        
        /* 三时段面板 */
        .meal-sections {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        .meal-panel {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }
        
        .meal-panel:hover {
            transform: translateY(-5px);
        }
        
        .meal-header {
            padding: 1.5rem;
            color: white;
            text-align: center;
            font-weight: bold;
            font-size: 1.2rem;
        }
        
        .breakfast-header {
            background: linear-gradient(135deg, #ff9500 0%, #ff6b00 100%);
        }
        
        .lunch-header {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        
        .dinner-header {
            background: linear-gradient(135deg, #6f42c1 0%, #e83e8c 100%);
        }
        
        .meal-content {
            padding: 1.5rem;
        }
        
        .recommendations-section {
            margin-bottom: 2rem;
        }
        
        .section-title {
            font-size: 1.1rem;
            font-weight: bold;
            margin-bottom: 1rem;
            color: #333;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .recommendations-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .dish-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 1rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid transparent;
        }
        
        .dish-card:hover {
            background: #e9ecef;
            border-color: #007bff;
            transform: translateY(-2px);
        }
        
        .dish-emoji {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }
        
        .dish-name {
            font-weight: bold;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }
        
        .dish-info {
            font-size: 0.8rem;
            color: #6c757d;
        }
        
        .full-menu {
            border-top: 1px solid #eee;
            padding-top: 1rem;
        }
        
        .menu-scroll {
            max-height: 300px;
            overflow-y: auto;
            padding-right: 0.5rem;
        }
        
        .menu-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem;
            border-radius: 8px;
            margin-bottom: 0.5rem;
            background: #f8f9fa;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .menu-item:hover {
            background: #e9ecef;
        }
        
        .menu-item-info {
            flex: 1;
        }
        
        .menu-item-name {
            font-weight: bold;
            margin-bottom: 0.25rem;
        }
        
        .menu-item-details {
            font-size: 0.8rem;
            color: #6c757d;
        }
        
        .menu-item-price {
            font-weight: bold;
            color: #007bff;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .meal-sections {
                grid-template-columns: 1fr;
            }
            
            .nutrition-overview {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .recommendations-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .quick-actions {
                flex-direction: column;
            }
        }
        
        /* 滚动条样式 */
        .menu-scroll::-webkit-scrollbar {
            width: 6px;
        }
        
        .menu-scroll::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        
        .menu-scroll::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }
        
        .menu-scroll::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
    </style>
</head>
<body>
    <!-- 顶部导航 -->
    <nav class="navbar">
        <div class="container">
            <div class="navbar-content">
                <a class="navbar-brand" href="/dashboard">🍃 智能营养管理系统</a>
                <div class="navbar-nav">
                    <a class="nav-link" href="/nutrition/dashboard">营养分析</a>
                    <a class="nav-link" href="/alerts">预警中心</a>
                    <a class="nav-link" href="/profile">个人中心</a>
                    <a class="nav-link" href="/logout">退出</a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container">
        <!-- 顶部显示区 -->
        <div class="top-section">
            <div class="user-welcome">
                <div class="welcome-text">
                    <h2>欢迎回来，<span th:text="${user.username}">用户</span>！</h2>
                    <p>今天是 <span id="currentDate"></span>，让我们开始健康的一天</p>
                </div>
                <div class="quick-actions">
                    <a href="/meals" class="btn btn-primary">
                        🍽️ 立即点餐
                    </a>
                    <a href="/nutrition/dashboard" class="btn btn-outline-primary">
                        📊 详细分析
                    </a>
                </div>
            </div>
            
            <!-- 营养进度概览 -->
            <div class="nutrition-overview">
                <div class="nutrition-card">
                    <div class="nutrition-icon">🔥</div>
                    <div class="nutrition-value" id="caloriesValue">
                        <span th:if="${progress != null}" th:text="${progress.calories}">0</span>
                        <span th:unless="${progress != null}">0</span>
                        /
                        <span th:if="${progress != null}" th:text="${progress.caloriesGoal}">2000</span>
                        <span th:unless="${progress != null}">2000</span>
                    </div>
                    <div class="nutrition-label">卡路里 (kcal)</div>
                </div>
                <div class="nutrition-card">
                    <div class="nutrition-icon">💪</div>
                    <div class="nutrition-value" id="proteinValue">
                        <span th:if="${progress != null}" th:text="${progress.protein}">0</span>
                        <span th:unless="${progress != null}">0</span>
                        /
                        <span th:if="${progress != null}" th:text="${progress.proteinGoal}">150</span>
                        <span th:unless="${progress != null}">150</span>
                    </div>
                    <div class="nutrition-label">蛋白质 (g)</div>
                </div>
                <div class="nutrition-card">
                    <div class="nutrition-icon">🌾</div>
                    <div class="nutrition-value" id="carbsValue">
                        <span th:if="${progress != null}" th:text="${progress.carbs}">0</span>
                        <span th:unless="${progress != null}">0</span>
                        /
                        <span th:if="${progress != null}" th:text="${progress.carbsGoal}">250</span>
                        <span th:unless="${progress != null}">250</span>
                    </div>
                    <div class="nutrition-label">碳水化合物 (g)</div>
                </div>
                <div class="nutrition-card">
                    <div class="nutrition-icon">🥑</div>
                    <div class="nutrition-value" id="fatValue">
                        <span th:if="${progress != null}" th:text="${progress.fat}">0</span>
                        <span th:unless="${progress != null}">0</span>
                        /
                        <span th:if="${progress != null}" th:text="${progress.fatGoal}">65</span>
                        <span th:unless="${progress != null}">65</span>
                    </div>
                    <div class="nutrition-label">脂肪 (g)</div>
                </div>
            </div>
        </div>

        <!-- 三时段面板 -->
        <div class="meal-sections">
            <!-- 早餐面板 -->
            <div class="meal-panel">
                <div class="meal-header breakfast-header">
                    🌅 早餐时光
                </div>
                <div class="meal-content">
                    <!-- 推荐菜品 -->
                    <div class="recommendations-section">
                        <div class="section-title">
                            ⭐ 为您推荐
                        </div>
                        <div class="recommendations-grid">
                            <div class="dish-card" th:each="dish : ${breakfastRecommendations}"
                                 th:data-dish-id="${dish.id}"
                                 th:data-dish-name="${dish.name}"
                                 data-meal-type="BREAKFAST"
                                 onclick="orderDishFromCard(this)">
                                <div class="dish-emoji">🍳</div>
                                <div class="dish-name" th:text="${dish.name}">菜品名称</div>
                                <div class="dish-info">
                                    <div th:text="${dish.calories} + ' kcal'">热量</div>
                                    <div th:text="'¥' + ${dish.price}">价格</div>
                                </div>
                            </div>
                            <div th:if="${#lists.isEmpty(breakfastRecommendations)}" class="dish-card">
                                <div class="dish-emoji">🍽️</div>
                                <div class="dish-name">暂无推荐</div>
                                <div class="dish-info">请稍后再试</div>
                            </div>
                        </div>
                    </div>

                    <!-- 完整菜单 -->
                    <div class="full-menu">
                        <div class="section-title">
                            📋 完整菜单
                        </div>
                        <div class="menu-scroll">
                            <div class="menu-item" th:each="dish : ${allDishes}"
                                 th:data-dish-id="${dish.id}"
                                 th:data-dish-name="${dish.name}"
                                 data-meal-type="BREAKFAST"
                                 onclick="orderDishFromCard(this)">
                                <div class="menu-item-info">
                                    <div class="menu-item-name" th:text="${dish.name}">菜品名称</div>
                                    <div class="menu-item-details" th:text="${dish.calories} + ' kcal | ' + ${dish.protein} + 'g 蛋白质'">营养信息</div>
                                </div>
                                <div class="menu-item-price" th:text="'¥' + ${dish.price}">价格</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 午餐面板 -->
            <div class="meal-panel">
                <div class="meal-header lunch-header">
                    ☀️ 午餐时光
                </div>
                <div class="meal-content">
                    <!-- 推荐菜品 -->
                    <div class="recommendations-section">
                        <div class="section-title">
                            ⭐ 为您推荐
                        </div>
                        <div class="recommendations-grid">
                            <div class="dish-card" th:each="dish : ${lunchRecommendations}"
                                 th:data-dish-id="${dish.id}"
                                 th:data-dish-name="${dish.name}"
                                 data-meal-type="LUNCH"
                                 onclick="orderDishFromCard(this)">
                                <div class="dish-emoji">🍛</div>
                                <div class="dish-name" th:text="${dish.name}">菜品名称</div>
                                <div class="dish-info">
                                    <div th:text="${dish.calories} + ' kcal'">热量</div>
                                    <div th:text="'¥' + ${dish.price}">价格</div>
                                </div>
                            </div>
                            <div th:if="${#lists.isEmpty(lunchRecommendations)}" class="dish-card">
                                <div class="dish-emoji">🍽️</div>
                                <div class="dish-name">暂无推荐</div>
                                <div class="dish-info">请稍后再试</div>
                            </div>
                        </div>
                    </div>

                    <!-- 完整菜单 -->
                    <div class="full-menu">
                        <div class="section-title">
                            📋 完整菜单
                        </div>
                        <div class="menu-scroll">
                            <div class="menu-item" th:each="dish : ${allDishes}"
                                 th:data-dish-id="${dish.id}"
                                 th:data-dish-name="${dish.name}"
                                 data-meal-type="LUNCH"
                                 onclick="orderDishFromCard(this)">
                                <div class="menu-item-info">
                                    <div class="menu-item-name" th:text="${dish.name}">菜品名称</div>
                                    <div class="menu-item-details" th:text="${dish.calories} + ' kcal | ' + ${dish.protein} + 'g 蛋白质'">营养信息</div>
                                </div>
                                <div class="menu-item-price" th:text="'¥' + ${dish.price}">价格</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 晚餐面板 -->
            <div class="meal-panel">
                <div class="meal-header dinner-header">
                    🌙 晚餐时光
                </div>
                <div class="meal-content">
                    <!-- 推荐菜品 -->
                    <div class="recommendations-section">
                        <div class="section-title">
                            ⭐ 为您推荐
                        </div>
                        <div class="recommendations-grid">
                            <div class="dish-card" th:each="dish : ${dinnerRecommendations}"
                                 th:data-dish-id="${dish.id}"
                                 th:data-dish-name="${dish.name}"
                                 data-meal-type="DINNER"
                                 onclick="orderDishFromCard(this)">
                                <div class="dish-emoji">🍽️</div>
                                <div class="dish-name" th:text="${dish.name}">菜品名称</div>
                                <div class="dish-info">
                                    <div th:text="${dish.calories} + ' kcal'">热量</div>
                                    <div th:text="'¥' + ${dish.price}">价格</div>
                                </div>
                            </div>
                            <div th:if="${#lists.isEmpty(dinnerRecommendations)}" class="dish-card">
                                <div class="dish-emoji">🍽️</div>
                                <div class="dish-name">暂无推荐</div>
                                <div class="dish-info">请稍后再试</div>
                            </div>
                        </div>
                    </div>

                    <!-- 完整菜单 -->
                    <div class="full-menu">
                        <div class="section-title">
                            📋 完整菜单
                        </div>
                        <div class="menu-scroll">
                            <div class="menu-item" th:each="dish : ${allDishes}"
                                 th:data-dish-id="${dish.id}"
                                 th:data-dish-name="${dish.name}"
                                 data-meal-type="DINNER"
                                 onclick="orderDishFromCard(this)">
                                <div class="menu-item-info">
                                    <div class="menu-item-name" th:text="${dish.name}">菜品名称</div>
                                    <div class="menu-item-details" th:text="${dish.calories} + ' kcal | ' + ${dish.protein} + 'g 蛋白质'">营养信息</div>
                                </div>
                                <div class="menu-item-price" th:text="'¥' + ${dish.price}">价格</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 设置当前日期
            const today = new Date();
            const options = {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                weekday: 'long'
            };
            document.getElementById('currentDate').textContent = today.toLocaleDateString('zh-CN', options);

            // 加载营养数据
            loadNutritionData();
        });

        // 加载营养数据
        function loadNutritionData() {
            fetch('/nutrition/api/progress')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('HTTP ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    // 控制台输出以便调试
                    console.debug('营养数据API返回:', data);
                    updateNutritionDisplay(data);
                })
                .catch(error => {
                    console.error('加载营养数据失败:', error);
                    // 使用默认值
                    updateNutritionDisplay({
                        totalCalories: 0,
                        targetCalories: 2000,
                        totalProtein: 0,
                        targetProtein: 150,
                        totalCarbs: 0,
                        targetCarbs: 250,
                        totalFat: 0,
                        targetFat: 65
                    });
                });
        }

        // 更新营养显示
        function updateNutritionDisplay(data) {
            // 兼容两种字段命名：
            // - API返回: calories, protein, carbs, fat 以及 caloriesGoal, proteinGoal, carbsGoal, fatGoal
            // - 前端原期待: totalCalories, targetCalories 等
            const totalCalories = (data.totalCalories ?? data.calories ?? 0);
            const targetCalories = (data.targetCalories ?? data.caloriesGoal ?? 2000);
            const totalProtein = (data.totalProtein ?? data.protein ?? 0);
            const targetProtein = (data.targetProtein ?? data.proteinGoal ?? 150);
            const totalCarbs = (data.totalCarbs ?? data.carbs ?? 0);
            const targetCarbs = (data.targetCarbs ?? data.carbsGoal ?? 250);
            const totalFat = (data.totalFat ?? data.fat ?? 0);
            const targetFat = (data.targetFat ?? data.fatGoal ?? 65);

            document.getElementById('caloriesValue').textContent =
                `${Math.round(totalCalories)} / ${targetCalories}`;
            document.getElementById('proteinValue').textContent =
                `${Math.round(totalProtein)} / ${targetProtein}`;
            document.getElementById('carbsValue').textContent =
                `${Math.round(totalCarbs)} / ${targetCarbs}`;
            document.getElementById('fatValue').textContent =
                `${Math.round(totalFat)} / ${targetFat}`;
        }

        // 从卡片点餐
        function orderDishFromCard(element) {
            const dishId = element.getAttribute('data-dish-id');
            const dishName = element.getAttribute('data-dish-name');
            const mealType = element.getAttribute('data-meal-type');

            orderDish(dishId, dishName, mealType);
        }

        // 点餐功能
        function orderDish(dishId, dishName, mealType) {
            // 显示确认对话框
            if (confirm(`确定要点餐 "${dishName}" 吗？\n餐别：${getMealTypeName(mealType)}`)) {
                // 发送点餐请求
                fetch('/meals/api/order', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        dishId: dishId,
                        mealType: mealType,
                        portionSize: 1.0
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage('success', `${dishName} 点餐成功！`);
                        // 重新加载营养数据
                        setTimeout(() => {
                            loadNutritionData();
                        }, 1000);
                    } else {
                        showMessage('error', data.message || '点餐失败');
                    }
                })
                .catch(error => {
                    console.error('点餐失败:', error);
                    showMessage('error', '网络错误，请重试');
                });
            }
        }

        // 获取餐别中文名称
        function getMealTypeName(mealType) {
            const names = {
                'BREAKFAST': '早餐',
                'LUNCH': '午餐',
                'DINNER': '晚餐',
                'SNACK': '小食'
            };
            return names[mealType] || mealType;
        }

        // 显示消息
        function showMessage(type, message) {
            // 移除现有消息
            const existingMessage = document.querySelector('.message-toast');
            if (existingMessage) {
                existingMessage.remove();
            }

            // 创建新消息
            const messageDiv = document.createElement('div');
            messageDiv.className = `message-toast alert alert-${type === 'success' ? 'success' : 'danger'}`;
            messageDiv.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 9999;
                padding: 1rem 1.5rem;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.15);
                background: ${type === 'success' ? '#d4edda' : '#f8d7da'};
                border: 1px solid ${type === 'success' ? '#c3e6cb' : '#f5c6cb'};
                color: ${type === 'success' ? '#155724' : '#721c24'};
                font-weight: 500;
                min-width: 300px;
                animation: slideIn 0.3s ease;
            `;

            messageDiv.innerHTML = `
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>${message}</span>
                    <button onclick="this.parentElement.parentElement.remove()"
                            style="background: none; border: none; font-size: 1.2rem; cursor: pointer; color: inherit; margin-left: 1rem;">
                        ×
                    </button>
                </div>
            `;

            document.body.appendChild(messageDiv);

            // 3秒后自动移除
            setTimeout(() => {
                if (messageDiv.parentElement) {
                    messageDiv.style.animation = 'slideOut 0.3s ease';
                    setTimeout(() => messageDiv.remove(), 300);
                }
            }, 3000);
        }

        // 添加动画样式
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOut {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>
